<template>
  <div class="pad-20 pad-r-10 circle-2-tab">
    <!-- status-0 待发布; status-1 待开始; status-2 进行中;  status-3 已结束; -->
    <div class="status-bar" :class="'status-'+promotionStatus" v-if="promotionStatus == '0'">待发布</div>
    <div class="status-bar" :class="'status-'+promotionStatus" v-if="promotionStatus == '1'">待开始</div>
    <div class="status-bar" :class="'status-'+promotionStatus" v-if="promotionStatus == '2'">进行中</div>
    <div class="status-bar" :class="'status-'+promotionStatus" v-if="promotionStatus == '3'">已停止</div>
    <div class="edit-main flex">
      <div class="edit-left">
        <div class="edit-main_bar mar-b-20">
          <div class="title-row font-22 font-color-6 pad-t-22 pad-b-22">活动设置</div>
          <el-form class="pad-b-30 pad-t-30">
            <el-form-item label="活动名称" label-width="80px" class="none-mar-b pad-b-20">
              <div class="mar-l-18 mar-r-12">
                <el-input placeholder="请输入活动名称，最多20个字" maxlength="20" style="width: 460px" v-model="form.title"
                  @change="changePromotionInfo" :disabled="disabledBoolean" />
              </div>
            </el-form-item>
            <el-form-item label="活动日期" label-width="80px" class="none-mar-b">
              <div class="mar-l-18 mar-r-12">
                <el-date-picker v-model="startTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="开始日期时间" :picker-options="pickerOptions" :disabled="disabledBoolean">
                </el-date-picker> -
                <el-date-picker v-model="endTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="结束日期时间" :picker-options="pickerOptions" :disabled="disabledBoolean">
                </el-date-picker>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <div class="edit-main_bar mar-b-18">
          <div class="title-row font-22 font-color-6 pad-t-22 pad-b-22">规则设置</div>
          <el-form class="pad-b-30 pad-t-30 pad-r-30">
            <el-form-item label="选择商品" label-width="80px" class="none-mar-b pad-b-20">
              <div class="mar-l-16 mar-r-12">
                <el-button type="primary" plain :disabled="disabledBoolean" @click="addGoods">添加商品
                </el-button>
              </div>
            </el-form-item>
            <div style="margin-left:96px;">
              <promotion-item-list ref="promotionItemList" :disabledBoolean="disabledBoolean">
              </promotion-item-list>
            </div>
          </el-form>
        </div>
      </div>
      <!-- <promotion-phone ref="promotionPhone"></promotion-phone> -->
      <div class="seckill-box edit-right">
        <img :src="seckillImg" class="width-320" alt="">
      </div>
    </div>
    <!-- 添加商品弹窗 -->
    <promotion-item-add ref="promotionItemAdd"></promotion-item-add>
    <!-- 设置商品活动价弹窗 -->
    <promotion-sku-price ref="promotionSkuPrice" :disabledBoolean="disabledBoolean"></promotion-sku-price>
    <div class="height-76"></div>
    <div class="footer-bar align-l v-align-c bg-color-white pad-t-20 pad-b-20 pad-r-20">
      <el-button type="default" class="mar-l-20 foot-btn mar-l-10 mar-r-10" size="medium" @click="goPageList">
        返回上一级</el-button>
      <el-button type="primary" class="mar-l-20 foot-btn mar-l-10 mar-r-10" size="medium"
        v-if="disabledBoolean && (promotionStatus == '0' || promotionStatus == '1')" @click="disabledBoolean = false">编辑
      </el-button>
      <el-button type="primary" class="mar-l-20 foot-btn mar-l-10 mar-r-10" size="medium" @click="savePromotion('0')"
        v-if="!disabledBoolean && promotionStatus == '0'">保存不发布</el-button>
      <el-button type="primary" class="mar-l-20 foot-btn mar-l-10 mar-r-10" size="medium" @click="submit"
        v-if="!disabledBoolean && promotionStatus == '0'">立即发布</el-button>
      <el-button type="primary" class="mar-l-20 foot-btn mar-l-10 mar-r-10" size="medium" @click="savePromotion('1')"
        v-if="!disabledBoolean && promotionStatus == '1'">保存</el-button>
    </div>
  </div>
</template>
<script>
  import promotionItemList from './components/promotion-item-list'
  import promotionItemAdd from './components/promotion-item-add'
  import promotionSkuPrice from './components/promotion-sku-price'
  import promotionPhone from './components/promotion-phone'
  import {
    savePromotion,
    getPromotionInfo
  } from '@/api/sell/promotion'
  import elDragDialog from '@/directive/el-dragDialog' // base on element-ui
  import seckillImg from '@/assets/images/seckill.jpg'
  export default {
    components: {
      promotionItemList,
      promotionItemAdd,
      promotionSkuPrice,
      promotionPhone
    },
    directives: {
      // 拖动窗口
      elDragDialog
    },
    data() {
      return {
        form: {
          title: '',
          backgroundColor: ''
        },
        startTime: '',
        endTime: '',
        activityType: 0,
        promotionStatus: '0',
        dialogFormVisible: false,
        disabledBoolean: false,
        copyBoolean: false,
        promotionId: '',
        goodsType: '0',
        seckillImg: seckillImg,
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() <= (Date.now() - (24 * 60 * 60 * 1000))
          }
        }
      }
    },
    // 初始化页面
    created() {},
    mounted() {
      const queryParams = this.getCurrentPage().query
      if (queryParams.disabledBoolean) {
        this.disabledBoolean = queryParams.disabledBoolean === 'true' || queryParams.disabledBoolean
      }
      if (queryParams.copyBoolean) {
        this.copyBoolean = queryParams.copyBoolean
        if (this.copyBoolean) {
          this.promotionStatus = '0'
        }
      }
      const promotionId = queryParams.promotionId
      this.activityType = queryParams.activityType
      if (promotionId) {
        this.promotionId = promotionId
        this.getPromotionInfo()
      }
    },
    filters: {},
    methods: {
      addGoods() {
        this.$refs.promotionItemAdd.dialogFormVisible = true
        this.$refs.promotionItemAdd.isSelectDataList()
      },
      changePromotionInfo() {
        this.$refs.promotionPhone.title = this.form.title
        this.$refs.promotionPhone.backgroundColor = this.form.backgroundColor
      },
      getPromotionInfo() {
        const that = this
        const data = {
          promotionId: this.promotionId
        }
        getPromotionInfo(data).then((response) => {
          if (response.isError) return
          that.form.title = response.data.title
          if (that.copyBoolean) {
            that.promotionStatus = '0'
          } else {
            that.promotionStatus = response.data.promotionStatus.toString()
          }
          that.form.backgroundColor = this.$utils.isExist(response.data.backgroundColor) ? response.data
            .backgroundColor : ''
          if (response.data.startTime && response.data.endTime) {
            that.startTime = response.data.startTime
            that.endTime = response.data.endTime
          }
          that.$bus.$emit('promotion-update', response.data)
          // that.changePromotionInfo()
        })
      },
      goPageList() {
        // this.$router.push('/goods/promotion/list/index')
        this.$router.go(-1)
      },
      submit() {
        this.$confirm('是否确认发布?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.savePromotion('1')
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      },
      savePromotion(promotionStatus) {
        const title = this.form.title
        const backgroundColor = this.$utils.isExist(this.form.backgroundColor) ? this.form.backgroundColor : ''
        const promotionId = this.promotionId
        const promotionGoodsList = this.$refs.promotionItemList.dataList
        if (promotionGoodsList == null || promotionGoodsList.length === 0) {
          this.$message.error('请选择活动商品!')
          return
        }
        var patt1 = new RegExp(/^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/)
        var patt2 = new RegExp(/^([0-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/)
        for (let i = 0; i < promotionGoodsList.length; i++) {
          const goods = promotionGoodsList[i]
          const skuFlag = goods.skuFlag
          if (skuFlag === 1) {
            const promotionGoodsSkuList = goods.promotionGoodsSkuList
            if (promotionGoodsSkuList == null || promotionGoodsSkuList.length === 0) {
              this.$message.error('部分数据异常，请前往设置!')
              return
            }
            for (let j = 0; j < promotionGoodsList.length; j++) {
              const promotionPrice = promotionGoodsList[j].promotionPrice
              if (!this.$utils.isExist(promotionPrice)) {
                this.$message.error('部分商品没有设置活动价格,请前去设置!')
                return
              }

              const fee = (promotionPrice * 1).toFixed(2)
              if (!patt1.test(fee) || fee < 0) {
                this.$message.error('请正确输入商品价格!')
                return
              }
              const distributeIncome = promotionGoodsList[j].distributeIncome
              if (!patt2.test(distributeIncome) || distributeIncome < 0) {
                this.$message.error('请输入正确分销佣金!')
                return
              }
              const shareMemberIncome = promotionGoodsList[j].shareMemberIncome
              if (!patt2.test(shareMemberIncome) || shareMemberIncome < 0) {
                this.$message.error('请输入正确的顾客分销商佣金!')
                return
              }
            }
          } else {
            const promotionPrice = goods.promotionPrice
            if (!this.$utils.isExist(promotionPrice)) {
              this.$message.error('部分商品没有设置活动价格,请前去设置!')
              return
            }
            const fee = (promotionPrice * 1).toFixed(2)
            if (!patt1.test(fee)) {
              this.$message.error('请正确输入商品价格!')
              return
            }
            const distributeIncome = goods.distributeIncome
            if (!patt2.test(distributeIncome) || distributeIncome < 0) {
              this.$message.error('请输入正确分销佣金!')
              return
            }
            const shareMemberIncome = goods.shareMemberIncome
            if (!patt2.test(shareMemberIncome) || shareMemberIncome < 0) {
              this.$message.error('请输入正确的顾客分销商佣金!')
              return
            }
          }
        }
        if (this.startTime === this.endTime) {
          this.$message.error('活动开始时间不能与结束时间一致!')
          return
        }
        if (!this.startTime) {
          this.$message.error('开始时间不能为空!')
        }
        if (!this.endTime) {
          this.$message.error('结束时间不能为空!')
        }
        const startTime = this.startTime
        const endTime = this.endTime
        const startDate = new Date(startTime).getTime()
        const endDate = new Date(endTime).getTime()
        if (endDate < startDate) {
          this.$message.error('结束时间要大于开始时间!')
          return
        }
        let data = {}
        // 复制秒杀 清空主键id
        if (this.copyBoolean) {
          const goodsList = []
          // 商品集合清空主键id
          for (let i = 0; i < promotionGoodsList.length; i++) {
            const itemGoods = promotionGoodsList[i]
            if (itemGoods.promotionGoodsSkuList || itemGoods.promotionGoodsSkuList.size > 0) {
              const goodsSkuList = []
              // 商品sku 清空主键 id
              for (let i = 0; i < itemGoods.promotionGoodsSkuList.length; i++) {
                const itemGoodsSku = itemGoods.promotionGoodsSkuList[i]
                itemGoodsSku.promotionGoodsId = ''
                itemGoodsSku.promotionSkuId = ''
                goodsSkuList.push(itemGoodsSku)
              }
              itemGoods.promotionGoodsSkuList = goodsSkuList
            }
            itemGoods.promotionGoodsId = ''
            itemGoods.promotionId = ''
            goodsList.push(itemGoods)
          }
          data = {
            title: title,
            promotionId: '',
            backgroundColor: backgroundColor,
            userType: '1',
            userId: this.getEnterpriseId(),
            promotionStatus: promotionStatus,
            startTime: startTime,
            endTime: endTime,
            promotionGoodsList: goodsList,
            activityType: this.activityType
          }
        } else {
          data = {
            title: title,
            backgroundColor: backgroundColor,
            userType: '1',
            userId: this.getEnterpriseId(),
            promotionId: promotionId,
            promotionStatus: promotionStatus,
            startTime: startTime,
            endTime: endTime,
            promotionGoodsList: promotionGoodsList,
            activityType: this.activityType
          }
        }
        savePromotion(data).then((response) => {
          if (response.isError) return
          if (response.code === 501 || response.code === 502 ||
            response.code === 503 || response.code === 504) {
            this.msgError(response.msg)
            let errorMsg = ''
            if (response.code === 502) {
              errorMsg = '已参加相同时段的社区团购活动'
            }
            if (response.code === 501) {
              errorMsg = '已参加相同时段的秒杀活动'
            }
            if (response.code === 503) {
              errorMsg = '商品不存在'
            }
            if (response.code === 504) {
              errorMsg = '商品已下架'
            }
            if (response.data != null && response.data.length > 0) {
              const promotionGoodsList = this.$refs.promotionItemList.dataList
              if (promotionGoodsList !== undefined && promotionGoodsList.length > 0) {
                for (let i = 0; i < promotionGoodsList.length; i++) {
                  const isError = response.data.some(function(value) {
                    return value === promotionGoodsList[i].goodsId
                  })
                  if (isError) {
                    promotionGoodsList[i].errorMsg = errorMsg
                  }
                }
                this.$refs.promotionItemList.changeData()
              }
            }
            return
          }
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          this.$router.push('/sell-promotion/list-promotion/index')
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .circle-2-tab {
    background: #FAFAFA;
    line-height: 1;
    min-height: 100%;

    /deep/ .el-form {
      background: white;
    }

    /deep/ .el-form-item {
      margin-bottom: unset;
      background: unset;
    }

    /deep/ .el-form-item__label {
      padding: 0;
    }
  }

  .status-bar {
    font-size: 18px;
    height: 75px;
    line-height: 75px;
    padding: unset;
    text-align: center;
    border-radius: unset;
    box-shadow: unset;
  }

  .status-1 {
    color: #409EFF;
    background: #E2F0FF;
  }

  .status-2 {
    color: #FF5A00;
    background: #FEEFE7;
  }

  .status-3 {
    color: #F33838;
    background: #FFE4E4;
  }

  .status-4 {
    color: #999999;
    background: #F0F0F0;
  }

  .edit-left {
    width: 78%;
    margin-right: 10px;
  }

  .seckill-box {
    margin-top: 65px;
  }

  .footer-bar {
    box-shadow: unset;
    border-top: 1px solid #F5F5F5;
    min-height: 96px;
  }

  .foot-btn {
    &:first-child {
      margin-left: 117px;
    }
  }

  .layer-over {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: 10;
  }

  // 页面总体布局
  .active-main {
    background: #f8f8f8;

    &:after {
      content: '';
      display: block;
      clear: both;
      font-size: 0;
    }

    .active-l {
      .main-content {
        padding-right: 4px;
        padding-left: 2px;
        height: 570px;
        overflow-x: hidden;
        overflow-y: auto;

        &::-webkit-scrollbar {
          width: 4px;
        }

        &::-webkit-scrollbar-thumb {
          border-radius: 10px;
          box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
          -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
          background: rgba(0, 0, 0, 0.2);
        }

        &::-webkit-scrollbar-track {
          box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
          -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
          border-radius: 0;
          background: rgba(0, 0, 0, 0.1);
        }

        h2 {
          margin: 0;
          font-size: 18px;
        }

        ul {
          padding: 0;
          margin: 0;

          &:after {
            content: '';
            display: block;
            clear: both;
            font-size: 0;
          }

          &.show-type-1 {
            li {
              .gooods-pic {
                img {
                  width: 100%;
                  height: 149px;
                  border-top-left-radius: 4px;
                  border-top-right-radius: 4px;
                }
              }
            }
          }

          &.show-type-2 {
            li {
              width: 48%;
              float: left;

              &:nth-child(odd) {
                margin-right: 4%;
              }

              .gooods-pic {
                img {
                  width: 100%;
                  height: 133px;
                  border-top-left-radius: 4px;
                  border-top-right-radius: 4px;
                }
              }

              .buy-now-type {
                display: none;
              }

              .price {
                label {
                  display: none;
                }
              }
            }
          }

          &.show-type-3 {
            li {
              display: -webkit-box;
              display: -webkit-flex;
              display: flex;
              flex-flow: row;
              align-items: center;
              padding: 0 5px 0 8px;

              .pic-box {
                margin-right: 6px;

                .gooods-pic {
                  img {
                    width: 82px;
                    height: 82px;
                  }
                }
              }

              .detail-box {
                -webkit-box-flex: 1;
                -webkit-flex: 1;
                flex: 1;
              }

              .tag {
                span {
                  padding: 1px 5px !important;
                }

                label {
                  padding: 1px 5px !important;
                }
              }

              .price {
                label {
                  display: none;
                }
              }

              .stock {
                display: none;
              }
            }
          }

          &.show-type-4 {
            li {
              display: -webkit-box;
              display: -webkit-flex;
              display: flex;
              flex-flow: row;
              align-items: center;
              padding: 8px 5px 8px 8px;

              &:nth-child(even) {
                .pic-box {
                  &.even {
                    display: none;
                  }

                  &.odd {
                    display: block;
                  }
                }
              }

              &:nth-child(odd) {
                .pic-box {
                  &.even {
                    display: block;
                  }

                  &.odd {
                    display: none;
                  }
                }
              }

              .pic-box {
                margin-right: 6px;

                .gooods-pic {
                  img {
                    width: 122px;
                    height: 122px;
                  }
                }
              }

              .detail-box {
                -webkit-box-flex: 1;
                -webkit-flex: 1;
                flex: 1;
                padding: 0 6px !important;
              }

              .desc {
                margin-top: -6px;
              }

              .tag {
                margin-top: -1px;
                margin-bottom: 0px;

                span {
                  padding: 1px 5px !important;
                }

                label {
                  padding: 1px 5px !important;
                }
              }

              .price {
                .flex-item {
                  >label {
                    display: -webkit-box;
                    display: -webkit-flex;
                    display: flex;
                    margin-top: -8px;
                  }
                }
              }

              .stock {
                display: none;
              }

              .info-bar {
                .buy-now-type {
                  display: none !important;
                }
              }

              .last-item {
                display: block !important;
                margin-top: 5px;
              }
            }
          }

          li {
            list-style-type: none;
            border-radius: 4px;
            box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);
            margin-bottom: 15px;

            &:last-child {
              margin-bottom: 0;
            }

            .pic-box {
              &.odd {
                display: none;
              }
            }

            .gooods-pic {
              img {
                display: block;
              }
            }

            .desc {
              height: 36px;
              line-height: 1.5;
              overflow: hidden;
              text-overflow: ellipsis;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
              word-break: break-word;
            }

            .last-item {
              display: none;
            }

            .info-bar {
              .tag {
                line-height: 1.3;

                span {
                  background: #fed807;
                  color: #333;
                  padding: 2px 5px;
                }

                label {
                  background: #272727;
                  color: #fff;
                  padding: 2px 5px;
                  min-width: 60px;
                  box-sizing: border-box;

                  i {
                    color: #ffc81b;
                    font-style: normal;
                  }
                }
              }

              .price {
                span {
                  color: #FF4949;
                }

                label {
                  text-decoration: line-through;
                }
              }

              .stock {
                color: #6e6e6e;
              }

              label {
                font-weight: normal;
              }
            }
          }
        }

        .picture-default {
          background: #fe8096;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }

    .active-r {
      padding: 20px;
      min-height: 609px;

      h2 {
        font-size: 18px;
        margin: 0;
      }

      .tips {
        color: #409eff;
      }

      .select-table {
        min-height: auto !important;
      }
    }
  }

  .category-style {
    color: #6290ff;
    font-size: 13px;
  }

  .title-line-2 {
    height: 40px;
    line-height: 1.4;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-word;
  }

  // 商品弹窗样式
  .goods-layer {
    h3 {
      margin: -10px 0 0 0;
      color: #303133;
      font-size: 18px;
      text-align: center;
    }

    .dialog-footer {
      position: absolute;
      left: 0;
      bottom: 20px;
      width: 100%;
    }

    .table-container {
      height: 500px;
      overflow-x: hidden;
      overflow-y: auto;
    }
  }

  // 左侧手机模型样式
  .diy-bg-main {
    .diy-phone {
      float: left;
      width: 340px;
      border: 1px solid #ddd;
      border-radius: 10px;
      background: #fff;
      padding: 10px;
      overflow: hidden;

      &.none-border {
        border: none;
        background: none;
        padding: 0px 10px;
        border-radius: 0;
      }
    }

    .diy-phone .phone-head {
      height: 44px;
      background: #fff;
      position: relative;
    }

    .diy-phone .phone-head:before {
      content: "";
      position: absolute;
      top: 15px;
      left: 112px;
      height: 8px;
      width: 8px;
      background: #ddd;
      border-radius: 8px;
    }

    .diy-phone .phone-head:after {
      content: "";
      position: absolute;
      top: 15px;
      left: 128px;
      height: 8px;
      width: 50px;
      background: #ddd;
      border-radius: 8px;
    }

    .diy-phone .phone-title {
      height: 17px;
      background: url(../../../../assets/images/wx-top-2.png) 0 0 no-repeat;
      background-size: 100% auto;
      padding: 0 50px;
      font-size: 15px;
      color: #333333;
      text-align: center;
      line-height: 68px;
      cursor: default;
      overflow: hidden;
      display: block;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
</style>
